import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { consoleApi } from '@/services/console'
import type {
    PurchaseOrderDto,
    PurchaseOrderExtendedDto,
    PurchaseOrderQueryDto,
    PurchaseOrderExtendedQueryDto,
    ApprovalDecisionDto,
    ApprovalFlowDto,
    PagedResultDto,
    ApiResult
} from '@/types/console'

export const usePurchaseOrderStore = defineStore('purchaseOrder', () => {
    // 状态定义
    const purchaseOrders = ref<PurchaseOrderDto[]>([])
    const extendedPurchaseOrders = ref<PurchaseOrderExtendedDto[]>([])
    const currentPurchaseOrder = ref<PurchaseOrderDto | null>(null)
    const currentExtendedPurchaseOrder = ref<PurchaseOrderExtendedDto | null>(null)
    const currentApprovalFlow = ref<ApprovalFlowDto | null>(null)

    // 分页信息
    const pagination = ref({
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        totalPages: 0,
        total: 0 // 兼容性属性
    })

    // 加载状态
    const loading = ref(false)
    const submitting = ref(false)

    // 查询条件
    const queryParams = ref<PurchaseOrderQueryDto>({
        pageIndex: 1,
        pageSize: 10,
        keyword: '',
        status: '',
        orderType: ''
    })

    const extendedQueryParams = ref<PurchaseOrderExtendedQueryDto>({
        pageIndex: 1,
        pageSize: 10,
        keyword: '',
        status: '',
        orderType: '',
        creator: '',
        includeApprovalFlow: false
    })

    // 计算属性
    const hasPurchaseOrders = computed(() => purchaseOrders.value.length > 0)
    const hasExtendedPurchaseOrders = computed(() => extendedPurchaseOrders.value.length > 0)

    // 按状态分组的采购订单
    const purchaseOrdersByStatus = computed(() => {
        const groups: Record<string, PurchaseOrderDto[]> = {}
        purchaseOrders.value.forEach(order => {
            const status = order.status || '未知'
            if (!groups[status]) {
                groups[status] = []
            }
            groups[status].push(order)
        })
        return groups
    })

    // 统计信息
    const statistics = computed(() => {
        const total = purchaseOrders.value.length
        const statusCounts = Object.entries(purchaseOrdersByStatus.value).reduce((acc, [status, orders]) => {
            acc[status] = orders.length
            return acc
        }, {} as Record<string, number>)

        return {
            total,
            statusCounts,
            totalAmount: purchaseOrders.value.reduce((sum, order) => sum + order.totalAmount, 0),
            pending: statusCounts['待审批'] || 0
        }
    })

    // 操作方法

    // 获取采购订单列表
    const fetchPurchaseOrders = async (query?: Partial<PurchaseOrderQueryDto>) => {
        loading.value = true
        try {
            const params = { ...queryParams.value, ...query }
            const result = await consoleApi.getPurchaseOrders(params)

            if (result.code === 200 && result.data) {
                purchaseOrders.value = result.data.items
                pagination.value = {
                    pageIndex: result.data.pageIndex,
                    pageSize: result.data.pageSize,
                    totalCount: result.data.totalCount,
                    totalPages: result.data.totalPages,
                    total: result.data.totalCount
                }
                queryParams.value = params
            }
            return result
        } catch (error) {
            console.error('获取采购订单列表失败:', error)
            return { success: false, code: 500, msg: '获取采购订单列表失败', data: null } as ApiResult<PagedResultDto<PurchaseOrderDto>>
        } finally {
            loading.value = false
        }
    }

    // 获取扩展采购订单列表
    const fetchExtendedPurchaseOrders = async (query?: Partial<PurchaseOrderExtendedQueryDto>) => {
        loading.value = true
        try {
            const params = { ...extendedQueryParams.value, ...query }
            const result = await consoleApi.getPurchaseOrdersExtended(params)

            if (result.code === 200 && result.data) {
                extendedPurchaseOrders.value = result.data.items
                pagination.value = {
                    pageIndex: result.data.pageIndex,
                    pageSize: result.data.pageSize,
                    totalCount: result.data.totalCount,
                    totalPages: result.data.totalPages,
                    total: result.data.totalCount
                }
                extendedQueryParams.value = params
            }
            return result
        } catch (error) {
            console.error('获取扩展采购订单列表失败:', error)
            return { success: false, code: 500, msg: '获取扩展采购订单列表失败', data: null } as ApiResult<PagedResultDto<PurchaseOrderExtendedDto>>
        } finally {
            loading.value = false
        }
    }

    // 获取采购订单详情
    const getPurchaseOrderDetail = async (id: number): Promise<ApiResult<PurchaseOrderDto>> => {
        loading.value = true
        try {
            const result = await consoleApi.getPurchaseOrderDetail(id)
            if (result.code === 200 && result.data) {
                currentPurchaseOrder.value = result.data
            }
            return result
        } catch (error) {
            console.error('获取采购订单详情失败:', error)
            return { success: false, code: 500, msg: '获取采购订单详情失败', data: null } as ApiResult<PurchaseOrderDto>
        } finally {
            loading.value = false
        }
    }

    // 获取扩展采购订单详情
    const getPurchaseOrderExtendedDetail = async (id: number): Promise<ApiResult<PurchaseOrderExtendedDto>> => {
        loading.value = true
        try {
            console.log('Store: 调用API获取扩展订单详情，ID:', id)
            const result = await consoleApi.getPurchaseOrderExtendedDetail(id)
            console.log('Store: API返回结果:', result)
            if (result.code === 200 && result.data) {
                currentExtendedPurchaseOrder.value = result.data
            }
            return result
        } catch (error) {
            console.error('获取扩展采购订单详情失败:', error)
            return { success: false, code: 500, msg: '获取扩展采购订单详情失败', data: null } as ApiResult<PurchaseOrderExtendedDto>
        } finally {
            loading.value = false
        }
    }

    // 创建采购订单
    const createPurchaseOrder = async (data: PurchaseOrderDto) => {
        submitting.value = true
        try {
            const result = await consoleApi.createPurchaseOrder(data)
            if (result.code === 200) {
                // 刷新列表
                await fetchPurchaseOrders()
            }
            return result
        } catch (error) {
            console.error('创建采购订单失败:', error)
            return { success: false, code: 500, msg: '创建采购订单失败', data: null } as ApiResult<PurchaseOrderDto>
        } finally {
            submitting.value = false
        }
    }

    // 创建扩展采购订单
    const createExtendedPurchaseOrder = async (data: PurchaseOrderExtendedDto) => {
        submitting.value = true
        try {
            const result = await consoleApi.createPurchaseOrderExtended(data)
            if (result.code === 200) {
                // 刷新列表
                await fetchExtendedPurchaseOrders()
            }
            return result
        } catch (error) {
            console.error('创建扩展采购订单失败:', error)
            return { success: false, code: 500, msg: '创建扩展采购订单失败', data: null } as ApiResult<PurchaseOrderExtendedDto>
        } finally {
            submitting.value = false
        }
    }

    // 更新采购订单
    const updatePurchaseOrder = async (data: PurchaseOrderDto) => {
        submitting.value = true
        try {
            const result = await consoleApi.updatePurchaseOrder(data)
            if (result.code === 200) {
                // 更新当前订单
                if (currentPurchaseOrder.value && currentPurchaseOrder.value.id === data.id) {
                    currentPurchaseOrder.value = result.data || data
                }
                // 刷新列表
                await fetchPurchaseOrders()
            }
            return result
        } catch (error) {
            console.error('更新采购订单失败:', error)
            return { success: false, code: 500, msg: '更新采购订单失败', data: null } as ApiResult<PurchaseOrderDto>
        } finally {
            submitting.value = false
        }
    }

    // 更新扩展采购订单
    const updateExtendedPurchaseOrder = async (data: PurchaseOrderExtendedDto) => {
        submitting.value = true
        try {
            const result = await consoleApi.updatePurchaseOrderExtended(data)
            if (result.code === 200) {
                // 更新当前订单
                if (currentExtendedPurchaseOrder.value && currentExtendedPurchaseOrder.value.id === data.id) {
                    currentExtendedPurchaseOrder.value = result.data || data
                }
                // 刷新列表
                await fetchExtendedPurchaseOrders()
            }
            return result
        } catch (error) {
            console.error('更新扩展采购订单失败:', error)
            return { success: false, code: 500, msg: '更新扩展采购订单失败', data: null } as ApiResult<PurchaseOrderExtendedDto>
        } finally {
            submitting.value = false
        }
    }

    // 删除采购订单
    const deletePurchaseOrder = async (id: number) => {
        submitting.value = true
        try {
            const result = await consoleApi.deletePurchaseOrder(id)
            if (result.code === 200) {
                // 从列表中移除
                purchaseOrders.value = purchaseOrders.value.filter(order => order.id !== id)
                extendedPurchaseOrders.value = extendedPurchaseOrders.value.filter(order => order.id !== id)
                // 清除当前订单
                if (currentPurchaseOrder.value?.id === id) {
                    currentPurchaseOrder.value = null
                }
                if (currentExtendedPurchaseOrder.value?.id === id) {
                    currentExtendedPurchaseOrder.value = null
                }
            }
            return result
        } catch (error) {
            console.error('删除采购订单失败:', error)
            return { success: false, code: 500, msg: '删除采购订单失败', data: false } as ApiResult<boolean>
        } finally {
            submitting.value = false
        }
    }

    // 审批相关操作

    // 提交审批
    const submitForApproval = async (id: number) => {
        submitting.value = true
        try {
            const result = await consoleApi.submitPurchaseOrderForApproval(id)
            if (result.code === 200) {
                // 刷新订单状态
                await getPurchaseOrderDetail(id)
                await fetchApprovalFlow(id)
            }
            return result
        } catch (error) {
            console.error('提交审批失败:', error)
            return { success: false, code: 500, msg: '提交审批失败', data: false } as ApiResult<boolean>
        } finally {
            submitting.value = false
        }
    }

    // 撤回订单
    const withdrawOrder = async (id: number) => {
        submitting.value = true
        try {
            const result = await consoleApi.withdrawPurchaseOrder(id)
            if (result.code === 200) {
                // 刷新订单状态
                await getPurchaseOrderDetail(id)
                await fetchApprovalFlow(id)
            }
            return result
        } catch (error) {
            console.error('撤回订单失败:', error)
            return { success: false, code: 500, msg: '撤回订单失败', data: false } as ApiResult<boolean>
        } finally {
            submitting.value = false
        }
    }

    // 审批订单
    const approveOrder = async (id: number, decision: ApprovalDecisionDto) => {
        submitting.value = true
        try {
            const result = await consoleApi.approvePurchaseOrder(id, decision)
            if (result.code === 200) {
                // 刷新订单状态
                await getPurchaseOrderDetail(id)
                await fetchApprovalFlow(id)
            }
            return result
        } catch (error) {
            console.error('审批订单失败:', error)
            return { success: false, code: 500, msg: '审批订单失败', data: false } as ApiResult<boolean>
        } finally {
            submitting.value = false
        }
    }

    // 获取审批流程
    const fetchApprovalFlow = async (id: number) => {
        loading.value = true
        try {
            const result = await consoleApi.getPurchaseOrderApprovalFlow(id)
            if (result.code === 200 && result.data) {
                currentApprovalFlow.value = result.data
            }
            return result
        } catch (error) {
            console.error('获取审批流程失败:', error)
            return { success: false, code: 500, msg: '获取审批流程失败', data: null } as ApiResult<ApprovalFlowDto>
        } finally {
            loading.value = false
        }
    }

    // 获取统计数据
    const fetchStatistics = async (startDate?: string, endDate?: string) => {
        try {
            return await consoleApi.getPurchaseOrderStatistics(startDate, endDate)
        } catch (error) {
            console.error('获取统计数据失败:', error)
            return { success: false, code: 500, msg: '获取统计数据失败', data: null }
        }
    }

    // 导出数据
    const exportOrders = async (query: PurchaseOrderExtendedQueryDto) => {
        try {
            return await consoleApi.exportPurchaseOrders(query)
        } catch (error) {
            console.error('导出数据失败:', error)
            return { success: false, code: 500, msg: '导出数据失败', data: new Blob() }
        }
    }

    // 重置状态
    const resetState = () => {
        purchaseOrders.value = []
        extendedPurchaseOrders.value = []
        currentPurchaseOrder.value = null
        currentExtendedPurchaseOrder.value = null
        currentApprovalFlow.value = null
        pagination.value = {
            pageIndex: 1,
            pageSize: 10,
            totalCount: 0,
            totalPages: 0,
            total: 0
        }
        queryParams.value = {
            pageIndex: 1,
            pageSize: 10,
            keyword: '',
            status: '',
            orderType: ''
        }
        extendedQueryParams.value = {
            pageIndex: 1,
            pageSize: 10,
            keyword: '',
            status: '',
            orderType: '',
            creator: '',
            includeApprovalFlow: false
        }
    }

    // 清除当前选中的订单
    const clearCurrentOrder = () => {
        currentPurchaseOrder.value = null
        currentExtendedPurchaseOrder.value = null
        currentApprovalFlow.value = null
    }

    return {
        // 状态
        purchaseOrders,
        extendedPurchaseOrders,
        currentPurchaseOrder,
        currentExtendedPurchaseOrder,
        currentApprovalFlow,
        pagination,
        loading,
        submitting,
        queryParams,
        extendedQueryParams,

        // 计算属性
        hasPurchaseOrders,
        hasExtendedPurchaseOrders,
        purchaseOrdersByStatus,
        statistics,

        // 方法
        fetchPurchaseOrders,
        fetchExtendedPurchaseOrders,
        getPurchaseOrderDetail,
        getPurchaseOrderExtendedDetail,
        // 方法别名
        createPurchaseOrder,
        createExtendedPurchaseOrder,
        updatePurchaseOrder,
        updateExtendedPurchaseOrder,
        deletePurchaseOrder,
        submitForApproval,
        withdrawOrder,
        approveOrder,
        fetchApprovalFlow,
        fetchStatistics,
        exportOrders,
        exportPurchaseOrders: exportOrders,
        resetState,
        clearCurrentOrder
    }
}) 